package com.zhx.basis.juc;

import java.util.concurrent.atomic.AtomicReference;

public class 自旋锁 {
    AtomicReference<Thread> atomicReference=new AtomicReference<>();

    public  void mylock(){
        Thread thread=Thread.currentThread();
        System.out.println("======="+Thread.currentThread().getName()+"=加锁=");
        //获取当前线程,如果有人占着一直循环直到释放
        while(!atomicReference.compareAndSet(null,thread)){
        }
    }
    public  void myunlock(){
        Thread thread=Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println("======="+Thread.currentThread().getName()+"=解锁=");
    }

    public static void main(String[] args) {

        自旋锁 z=new 自旋锁();
        new Thread(()->{
            z.mylock();
            try { Thread.sleep(5000); } catch (InterruptedException e) {  e.printStackTrace(); }
            z.myunlock();
        },"线程A").start();

        //休眠main线程为了让线程A能够先执行
        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace(); }

        //由于线程A一直持有锁,线程B一直在自旋循环,直到5秒钟结束A释放了锁,B接着释放锁
        new Thread(()->{
            z.mylock();
            z.myunlock();
        },"线程B").start();
    }
}
